//
//  PersonInfoViewController.m
//  ppkc2016
//
//  Created by 拼凑的断音 on 16/3/10.
//  Copyright © 2016年 拼凑的断音. All rights reserved.
//

#import "PersonInfoViewController.h"
#import "XXTool.h"

#import "PersonInfoHeadCell.h"
#import "PersonInfoInputCell.h"
#import "PersonInfoModel.h"
#import "MainViewController.h"

#import "PresentProjectMainCotroller.h"
#import "XTCPersonInfoExitButtonCell.h"
#import "XVCIndexSelect.h"

#import "SelectRegistrationStatusViewController.h"

@interface PersonInfoViewController ()<UITableViewDataSource,UITableViewDelegate,UIPickerViewDelegate,UIPickerViewDataSource,UIAlertViewDelegate,PersonInfoInputCellDelegate,PersonInfoHeadCellDelegate,XTCPersonInfoExitButtonCellDelegate>

@property (nonatomic,strong) UITableView *tableview;

@property (nonatomic,strong) UIPickerView *sexPicker;

@property (nonatomic,strong) NSString*  index;

@property(nonatomic) Boolean needFlush;

@end

@implementation PersonInfoViewController
{
    NSMutableArray <PersonInfoInputModel*> *data;
    NSArray * sexArray;
    NSString* headPhotoUrl;
    UIImage* userSelectedHead;
    UITextField * sexInputTextField;
    NSIndexPath *firstTextFielfIndexPath;  //点击输入框后该输入框对应的cell
    
    UITextField *inputNumberType;
}
-(UITableView*)tableview
{
    if (_tableview==nil)
    {
        _tableview = [[UITableView alloc] init];
        _tableview.delegate = self;
        _tableview.dataSource = self;
        _tableview.separatorColor = [XXTool colorWithLine];
        _tableview.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        [_tableview setTableFooterView:[[UIView alloc] initWithFrame:CGRectZero]];
        [self.view addSubview:_tableview];
    }
    return _tableview;
}

-(UIPickerView*)sexPicker
{
    if (_sexPicker==nil)
    {
        _sexPicker = [[UIPickerView alloc] init];
        _sexPicker.delegate = self;
        _sexPicker.backgroundColor = [UIColor whiteColor];
        _sexPicker.dataSource = self;
    }
    return _sexPicker;
}

-(void)initParameter
{
    data = [[NSMutableArray alloc] init];
    for (int i=0; i<12; i++)
    {
        PersonInfoInputModel *temp = [[PersonInfoInputModel alloc] init];
        if (i<=5)
        {
            temp.isRequired = YES;
        }
        else
        {
            temp.isRequired = NO;
        }
        temp.isLeibie=false;
        if (i==0)
        {
            temp.cueString = NSLocalizedString(@"姓名", nil);
        }
        else if (i==1)
        {
            temp.cueString = NSLocalizedString(@"手机", nil);
        }
        else if (i==2)
        {
            temp.cueString = NSLocalizedString(@"邮箱", nil);
        }
        else if (i==3)
        {
            temp.cueString = NSLocalizedString(@"公司名", nil);
        }
        else if (i==4)
        {
            temp.cueString = NSLocalizedString(@"职位", nil);
        }
        else if (i==5)
        {
            temp.cueString = NSLocalizedString(@"感兴趣产品", nil);
            temp.isLeibie=true;
        }
        else if (i==6)
        {
            temp.cueString = NSLocalizedString(@"固话", nil);
        }
        else if (i==7)
        {
            temp.cueString = NSLocalizedString(@"国家", nil);
        }
        else if (i==8)
        {
            temp.cueString = NSLocalizedString(@"城市", nil);
        }
        else if (i==9)
        {
            temp.cueString = NSLocalizedString(@"性别", nil);
        }
        else if (i==10)
        {
            temp.cueString = NSLocalizedString(@"地址", nil);
        }
        else if (i==11)
        {
            temp.cueString = NSLocalizedString(@"传真", nil);
        }
        temp.inputString = @"";
        [data addObject:temp];
    }

    sexArray = @[NSLocalizedString(@"男", nil),NSLocalizedString(@"女", nil)];
}

-(void)initUI
{
    [self.navigationItem setTitle:NSLocalizedString(@"我", nil)];
    [self.view setBackgroundColor:[XXTool colorWithBackGround]];
     [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"更多"] style:UIBarButtonItemStylePlain target:self action:@selector(clickleft)]];
//    if (_useType==PersonInfoViewControllerDefault)
//    {
//        [self.navigationItem setLeftBarButtonItem:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"更多"] style:UIBarButtonItemStylePlain target:self action:@selector(clickleft)]];
//    }
//    else
//    {
//        self.navigationItem.hidesBackButton = YES;
//    }
    [self.navigationItem setRightBarButtonItem:[[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"提交", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickPersonInfoSubmitButton)]];
    [self tableview];
    [self sexPicker];
    
    _needFlush=true;
    
    [self getUserInfo];
    
}

-(void)refreshLayout:(CGRect)frame
{
    _tableview.frame = CGRectMake(0, 0, frame.size.width
                                      , frame.size.height);
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self didUserInfoSetup];
}

-(void)getUserInfo{
     NSLog(@"getUserInfo");
    // 获取 个人信息
    [PersonInfoModel getPersonInfoWithCompletion:^(PersonInfoModel *info) {
        if (info != nil)
        {
            headPhotoUrl = info.head_img;
            [UserInfo shareUserInfo].userHeadImgUrl = info.head_img;
            userSelectedHead = nil;   //页面每次出现上次选择的头像都应该清空
            data = [[NSMutableArray alloc] init];
            
            for (int i=0; i<12; i++)
            {
                PersonInfoInputModel *temp = [[PersonInfoInputModel alloc] init];
                if (i<=5)
                {
                    temp.isRequired = YES;
                }
                else
                {
                    temp.isRequired = NO;
                }
                temp.isLeibie=false;
                if (i==0)
                {
                    temp.cueString = NSLocalizedString(@"姓名", nil);
                    temp.inputString = info.username;
                }
                else if (i==1)
                {
                    temp.cueString = NSLocalizedString(@"电话", nil);
                    temp.inputString = info.userphone;
                }
                else if (i==2)
                {
                    temp.cueString = NSLocalizedString(@"邮箱", nil);
                    temp.inputString = info.usermail;
                }
                else if (i==3)
                {
                    temp.cueString = NSLocalizedString(@"公司名", nil);
                    temp.inputString = info.cpname;
                }
                else if (i==4)
                {
                    temp.cueString = NSLocalizedString(@"职位", nil);
                    temp.inputString = info.userposition;
                }
                else if (i==5)
                {
                    temp.cueString = NSLocalizedString(@"感兴趣产品", nil);
                    NSString *searchText = @"";
                    if([XXTool didCurrentLanguageChinese])
                    {
                        temp.inputString = info.interesting_zh;
                        searchText = @"index_name_cn";
                    }
                    else
                    {
                        temp.inputString = info.interesting_en;
                        searchText = @"index_name_en";
                    }
                    temp.inputString = [temp.inputString stringByReplacingOccurrencesOfString:@"\n" withString:@"\r"];
                    RLMResults <RXMLExhibitorIndexModel *>*indexResult = [RXMLExhibitorIndexModel objectsInRealm:[RLMRealm realmWithPath:[XXTool dataBasePath]] where:[NSString stringWithFormat:@"%@ == '%@'",searchText,temp.inputString]];
                    if (indexResult.count > 0)
                    {
                        temp.index = indexResult.firstObject.index_NO;
                    }
                    
                    temp.isLeibie=true;
                }
                else if (i==6)
                {
                    temp.cueString = NSLocalizedString(@"固话", nil);
                    temp.inputString = info.usergh;
                }
                else if (i==7)
                {
                    temp.cueString = NSLocalizedString(@"国家", nil);
                    temp.inputString = info.usercountry;
                }
                else if (i==8)
                {
                    temp.cueString = NSLocalizedString(@"城市", nil);
                    temp.inputString = info.usercity;
                }
                else if (i==9)
                {
                    temp.cueString = NSLocalizedString(@"性别", nil);
                    temp.inputString = info.usersex;
                }
                else if (i==10)
                {
                    temp.cueString = NSLocalizedString(@"地址", nil);
                    temp.inputString = info.useradress;
                }
                else if (i==11)
                {
                    temp.cueString = NSLocalizedString(@"传真", nil);
                    temp.inputString = info.userfax;
                }
                [data addObject:temp];
            }
            [_tableview reloadData];
            [SVProgressHUD dismiss];
        }
    }];

}

-(void)didUserInfoSetup
{
    NSLog(@"didUserInfoSetup");
    if(_needFlush){
        [self getUserInfo];
    }
    
}

#pragma mark UITableViewDataSource
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0)
    {
        NSString *reuseIdentifer = @"PersonInfoHeadCell";
        PersonInfoHeadCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifer];
        if (cell==nil)
        {
            cell = [[PersonInfoHeadCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifer];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
        }
        if (userSelectedHead==nil)
        {
            [cell setUserHeadImg:headPhotoUrl compltion:^(UIImage *img) {
                userSelectedHead = img;
            }];
        }
        else
        {
            [cell setUserHeadImgWithUIImage:userSelectedHead];
        }
        return cell;
    }
    else if (indexPath.row==data.count+1)
    {
        XTCPersonInfoExitButtonCell *cell = [XTCPersonInfoExitButtonCell cellSelectionStyleNoneWithTableView:tableView];
        cell.delegate = self;
        return cell;
    }
    else
    {
        NSString *reuseIdentifer = @"PersonInfoInputCell";
        PersonInfoInputCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifer];
        if (cell==nil)
        {
            cell = [[PersonInfoInputCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifer];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.delegate = self;
        }
        [cell setCellWithData:data[indexPath.row-1]];
        return cell;
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1+data.count+1;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row==0)
        return 173;
    else if (indexPath.row==data.count+1)
        return 55;
    return 55;
}

#pragma mark UITableViewDelegate
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 6)
    {
        // 判断是否为类别项
        _needFlush=false;
        [XVCIndexSelect pushIndexSelectVCWithSourceVCProfile:self isUseCountryShow:NO nowType:XVCIndexProfile Compeletation:^(NSString *block) {
            
            NSArray *array = [block componentsSeparatedByString:@"-"];

            data[indexPath.row-1].inputString=array[0];
            data[indexPath.row-1].index=array[1];
            
            
            PersonInfoInputCell *cell=[tableView cellForRowAtIndexPath:indexPath];
            [cell setLeibieInfo:array[0]];
            
            // 刷新某一个 cell
//            [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationNone];
        }];
    }
}

#pragma mark pickerViewDataSource
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    return 2;
}

#pragma mark pickerViewDelegate
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    return sexArray[row];
}

#pragma mark PersonInfoInputCellDelegate
-(void)inputTextDidChangeWithPersonInfoInputCell:(PersonInfoInputCell *)cell changeText:(NSString *)text
{
    //NSUInteger row = [_tableview indexPathForCell:cell].row;
//    PersonInfoInputModel *temp = [data objectAtIndex:row-1];
    PersonInfoInputModel *temp = [data objectAtIndex:firstTextFielfIndexPath.row-1];
    temp.inputString = text;
}

-(BOOL)personInfoInputCell:(PersonInfoInputCell *)cell textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
//    NSUInteger row = [_tableview indexPathForCell:cell].row;
//    PersonInfoInputModel *temp = [data objectAtIndex:row-1];
    PersonInfoInputModel *temp = [data objectAtIndex:firstTextFielfIndexPath.row-1];
    
    if ([string isEqualToString:@"\n"])
    {
        return YES;
    }
    if([string isEqualToString:@""])
    {
        return YES;
    }
    
    if ([temp.cueString isEqualToString:NSLocalizedString(@"电话", nil)]||[temp.cueString isEqualToString:NSLocalizedString(@"固话", nil)])
    {
        NSUInteger lengthOfString = string.length;
        for (NSInteger loopIndex = 0; loopIndex < lengthOfString; loopIndex++)
        {//只允许数字输入
            unichar character = [string characterAtIndex:loopIndex];
            if (character < 48)
                return NO; // 48 unichar for 0
            if (character > 57)
                return NO; // 57 unichar for 9
            
        }
        // Check for total length
        NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
        
        if (proposedNewLength > 11)
            return NO;//限制长度
        return YES;
    }
    else
    {
        return YES;
    }
    
}

-(void)personInfoInputCell:(PersonInfoInputCell *)cell textFieldDidBeginEditing:(UITextField *)textField
{
    inputNumberType = textField;
    firstTextFielfIndexPath = [_tableview indexPathForCell:cell];

    PersonInfoInputModel *temp = [data objectAtIndex:firstTextFielfIndexPath.row-1];
    if ([temp.cueString isEqualToString:NSLocalizedString(@"性别", nil)]||[temp.cueString isEqualToString:NSLocalizedString(@"电话", nil)]||[temp.cueString isEqualToString:NSLocalizedString(@"固话", nil)])
    {
        sexInputTextField = textField;
        //textview编辑完成
        UIToolbar * topView = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, 30)];
        topView.backgroundColor = [XXTool colorWithBackGround];
        [topView setBarStyle:UIBarStyleDefault];
        UIBarButtonItem * btnSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        
        NSArray * buttonsArray = nil;
        if ([temp.cueString isEqualToString:NSLocalizedString(@"性别", nil)])
        {
            UIBarButtonItem * cancelButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"取消", nil) style:UIBarButtonItemStylePlain target:self action:@selector(clickTextFieldCancel)];
            [cancelButton setTintColor:[XXTool colorWithProject]];
            
            
            UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"完成", nil) style:UIBarButtonItemStyleDone target:self action:@selector(clickTextFieldDone)];
            [doneButton setTintColor:[XXTool colorWithProject]];
            
            buttonsArray = [NSArray arrayWithObjects:cancelButton, btnSpace, doneButton, nil];
            
            
            textField.inputView = _sexPicker;
            textField.keyboardType = UIKeyboardTypeDefault;
        }
        else
        {
            UIBarButtonItem * doneButton = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"完成", nil) style:UIBarButtonItemStyleDone target:self action:@selector(clickNumberInputDone)];
            [doneButton setTintColor:[XXTool colorWithProject]];
            
            textField.inputView = nil;
            textField.keyboardType = UIKeyboardTypeNumberPad;
            buttonsArray = [NSArray arrayWithObjects:btnSpace,doneButton, nil];
        }
        
        [topView setItems:buttonsArray];
        
        [textField setInputAccessoryView:topView];
    }
    else
    {
        textField.keyboardType = UIKeyboardTypeDefault;
        textField.inputView = nil;
        [textField setInputAccessoryView:nil];
    }

}

-(void)clickTextFieldCancel
{
    [sexInputTextField resignFirstResponder];
}

-(void)clickTextFieldDone
{
    PersonInfoInputModel *temp = data[8];
    temp.inputString = sexArray[[_sexPicker selectedRowInComponent:0]];
    sexInputTextField.text = temp.inputString;
    [self clickTextFieldCancel];
}

-(void)clickNumberInputDone
{
    if (inputNumberType)
    {
        [inputNumberType resignFirstResponder];
    }
}

#pragma mark PersonInfoExitButtonDelegate
-(void)personInfoExitCellDidClickButton
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"提示", nil)
                                                    message:NSLocalizedString(@"是否确认注销?", nil)
                                                   delegate:self
                                          cancelButtonTitle:NSLocalizedString(@"取消", nil) otherButtonTitles:NSLocalizedString(@"确定", nil), nil];
    [alter show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex==1)
    {
        [self removeUserInfo];
    }
}

-(void)removeUserInfo
{
    //删除用户信息
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:userIDString];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:userPassword];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:userIsExhibitor];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:userName];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:userCompany];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:userHeadImgUrl];
    [[NSUserDefaults standardUserDefaults]  synchronize];
    [UserInfo shareUserInfo].userID = @"";
    [UserInfo shareUserInfo].userPassword = @"";
    [UserInfo shareUserInfo].isExhibitor = NO;
    [UserInfo shareUserInfo].userName = @"";
    [UserInfo shareUserInfo].userCompany = @"";
    [UserInfo shareUserInfo].userHeadImgUrl = @"";
    
    [JPUSHService setTags:[NSSet setWithArray:@[@"tag1"]]  completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
    } seq:0];
    
    [[NSNotificationCenter defaultCenter] postNotificationName:@"DidSuccessFullSetupUserInfo" object:nil];
    
    [self.navigationController popViewControllerAnimated:NO];
    [self presentViewController:[[MainViewController alloc] initWithRootViewController:[[SelectRegistrationStatusViewController alloc] init]] animated:YES completion:^{
        
    }];
}

#pragma mark PersonInfoHeadCellDelegate
-(void)PersonInfoHeadCellDidSelectedHead:(UIImage *)img
{
    userSelectedHead = img;
}

-(void)clickleft
{
    //[self.navigationController.sideViewController showLeftView];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)clickPersonInfoSubmitButton
{
    _needFlush=true;
    for (int i=0; i<data.count; i++)
    {
        PersonInfoInputModel *temp = data[i];
        if (i<=5)
        {
            if ([temp.inputString isEqualToString:@""])
            {
                switch (i) {
                    case 0:
                        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"姓名是必填项", nil)];
                        return;
                        break;
                    case 1:
                        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"电话是必填项", nil)];
                        return;
                        break;
                    case 2:
                        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"邮箱是必填项", nil)];
                        return;
                        break;
                    case 3:
                        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"公司名是必填项", nil)];
                        return;
                        break;
                    case 4:
                        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"职位是必填项", nil)];
                        return;
                        break;
                    case 5:
                        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"类别是必填项", nil)];
                        return;
                        break;
                        
                    default:
                        break;
                }
            }
        }
        else //只判断必填项
        {
            break;
        }
    }
    
    PersonInfoInputModel *temp = data[2];
    if (![XXTool validateEmail:temp.inputString])
    {
        [SVProgressHUD showInfoWithStatus:NSLocalizedString(@"请输入有效邮箱", nil)];
        return;
    }
    
    PersonInfoModel *useInfo = [[PersonInfoModel alloc] init];
    useInfo.username = [data[0] inputString];
    useInfo.userphone = [data[1]inputString];
    useInfo.usermail = [data[2]inputString];
    useInfo.cpname = [data[3]inputString];
    useInfo.userposition = [data[4]inputString];
    useInfo.interesting_zh= [data[5]inputString];
    useInfo.usergh = [data[6]inputString];
    useInfo.usercountry = [data[7]inputString];
    useInfo.usercity = [data[8]inputString];
    useInfo.usersex = [data[9]inputString];
    useInfo.useradress = [data[10]inputString];
    useInfo.userfax = [data[11]inputString];
    //头像优先选择在imageview上面的头像
   
    useInfo.headImage = userSelectedHead;
    useInfo.leibie_index=[data[5] index];
    
    [PersonInfoModel personInfoBook:useInfo completion:^(BOOL isSuccess) {
        if (isSuccess)
        {
            [SVProgressHUD showSuccessWithStatus:NSLocalizedString(@"保存成功", nil)];
            // 保存资料成功后，打开侧边栏
            //[self.navigationController.sideViewController showLeftView];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"DidSuccessFullSetupUserInfo" object:nil];
            
            
            if (_useType==PersonInfoViewControllerDidExhibitorPerfect) //展商信息补充成功
            {
                [[NSNotificationCenter defaultCenter] postNotificationName:@"exhibitorSuccess" object:nil userInfo:@{@"is":[NSNumber numberWithBool:self.isNeedGoIntro]}];
                [self dismissViewControllerAnimated:YES completion:^{
                    
                }];
            }
            else
            {
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
    }];
}

#pragma mark api
+(void)pushPersonInfoVCWithSourceVC:(UIViewController *)sourceVC personInfoViewControllerType:(PersonInfoViewControllerType)type
{
    PersonInfoViewController *vc = [[PersonInfoViewController alloc] init];
    vc.useType = type;
    if (sourceVC)
    {
        [sourceVC.navigationController pushViewController:vc animated:YES];
    }
}

+(void)presentPersonInfoVCWithSourceVC:(UIViewController *)sourceVC personInfoViewControllerType:(PersonInfoViewControllerType)type
{
    PersonInfoViewController *vc = [[PersonInfoViewController alloc] init];
    vc.useType = type;
    if (sourceVC)
    {
        [sourceVC presentViewController:[[MainViewController alloc] initWithRootViewController:vc]
                               animated:YES
                             completion:^{
                                 
                             }];
    }
}

@end
